package Multithreading.Exercise007;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;

/**
 * ClassName:MyThread
 * Package:Multithreading.Exercise007
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/3/7-8:49
 * @Version:v1.0
 */
public class MyThread extends Thread {
    //共享数据
    //100块,分成3个包
    static BigDecimal money = BigDecimal.valueOf(100);
    static int count = 3;
    //最小中奖金额
    static final BigDecimal MIN = BigDecimal.valueOf(0.01);

    @Override
    public void run() {
        synchronized (MyThread.class) {
            if (count == 0) {
                //判断,共享数据是否到了末尾(已经到了末尾)
                System.out.println(getName() + "没有红包了");
            } else {
                //判断,共享数据是否到末尾
                BigDecimal prize;
                if (count == 1) {
                    //表示此时是最后一个红包
                    //就不需要再次随机,剩余所有的钱都是中奖金额
                    prize = money;
                } else {
                    //表示第一次,第二次(随机)
                    //随机抽奖范围
                    double bounds = money.subtract(BigDecimal.valueOf(count - 1).multiply(MIN)).doubleValue();
                    Random r = new Random();
                    prize = BigDecimal.valueOf(r.nextDouble(bounds));
//                    if (prize < MIN) {
//                        prize = MIN;
//                    }
                }
                //设置抽中红包,小数点保留两位,四舍五入
                prize = prize.setScale(2, RoundingMode.HALF_UP);
                //从money当中,去掉当前中奖的金额
                money = money.subtract(prize);
                count--;
                System.out.println(getName() + "抢到了" + prize + "元");
            }
        }
    }
}
